package cn.edu.swu.film;

import cn.edu.swu.db.DBEngine;
import cn.edu.swu.db.RecordVisitor;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class FilmRepo {
    private static FilmRepo instance = new FilmRepo();

    private FilmRepo(){
    }

    public static FilmRepo getInstance() {
        return instance;
    }

    public List<Film> getAll() throws SQLException {
        String sql = "SELECT `id`, `name`, `star`, `time`, `grade` , `describe` FROM `film`";
        return DBEngine.getInstance().query(sql, new RecordVisitor<Film>() {
            @Override
            public Film visit(ResultSet rs) throws SQLException {
                return FilmRepo.getFilmFromResultset(rs);
            }
        });
    }

    private static Film getFilmFromResultset(ResultSet rs) throws SQLException {
        Film film = new Film();
        film.setId(rs.getLong("id"));
        film.setName(rs.getString("name"));
        film.setStar(rs.getString("star"));
        film.setDescribe(rs.getString("describe"));
        film.setGrade(rs.getFloat("grade"));
        film.setTime(rs.getString("time"));
        return film;
    }

    public void savefilm(Film film) throws SQLException {
        if (film.getId() > 0) {
            this.updateFilm(film);
        } else {
            this.insertFilm(film);
        }
    }

    private void insertFilm(Film film) throws SQLException {
        String template =
                "INSERT INTO `film`(`name`, `star`, `grade`, `time`, `describe`) " +
                        "VALUES (\"%s\", \"%s\", %s, \"%s\", \"%s\")";
        String sql = String.format(template, film.getName(), film.getStar(), film.getGrade(), film.getTime(),film.getDescribe());
        DBEngine.getInstance().execute(sql);
    }

    private void updateFilm(Film film) throws SQLException {
        String template =
                "UPDATE `film` SET `name`=\"%s\", `star`=\"%s\", `grade`=%s, `time`=\"%s\",`describe`=\"%s\" " +
                        "WHERE `id`=%s";
        String sql = String.format(template, film.getName(),
                film.getStar(),  film.getGrade(), film.getTime(),film.getDescribe(),film.getId());
        DBEngine.getInstance().execute(sql);
    }

    public void deleteFilm(Long id) throws SQLException {
        String template = "DELETE FROM `film` WHERE `id` = %s";
        String sql = String.format(template, id);
        DBEngine.getInstance().execute(sql);
    }
    public Film getById(String id) throws SQLException {
        String sql = "SELECT * FROM `film` WHERE `id` = %s";
        List<Film> films = DBEngine.getInstance().query(
                String.format(sql, id), new RecordVisitor<Film>() {
                    @Override
                    public Film visit(ResultSet rs) throws SQLException {
                        return FilmRepo.getFilmFromResultset(rs);
                    }
                });
        return films.size() == 0 ? null : films.get(0);
    }
}